<?php
namespace app\admin\controller;
use think\Controller;
use think\view;
use think\Db;
use think\Session;
use think\Request;
class Wx extends Controller {

    function show($status,$message,$data=array()){
        $reuslt = array(
            'status'=>$status,
            'message'=>$message,
            'data'=>$data,
        );
        exit(json_encode($reuslt)) ;   //输出一条信息 并退出当前脚本
    }

     /**
      * 登录接口
      */
     public function login(){
       if($_POST){
           //获取openID
           $code = $_POST['code'];
           $curl = curl_init();
           //配置appid
           $appid = "wxa7b85cb5e6a53427";
           //配置appscret
           $secret = "694c0aeb01b6b43bdc58cacbc1630cd9";
           //api接口
           $url =    'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';


           curl_setopt($curl, CURLOPT_URL, $url);
           curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
           curl_setopt($curl, CURLOPT_HEADER, 0);
           curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
           curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

           $str = curl_exec($curl);

           //释放curl句柄
           curl_close($curl);


//        print_r($str);
           $str = json_decode($str,true);
           $openid = $str['openid'];


           $username = $_POST['username'];
           $password = $_POST['password'];
           $user  =Db::name('user')->where(array(
               'username'=>$username,
               'password'=>md5($password)
           ))->find();
           if($user){
               if($user['state'] == 2){
                   $this->show(0,'该账号已禁用');
               }else{
                   //检测openid 是否存在
                   if(!$user['openid']){
                       $data['id'] = $user['id'];
                       $data['openid'] = $openid;

                        Db::name('user')->update($data);
                   }
                   $this->show(1,'获取成功',$user);
               }

           }else{
               $this->show(0,'账号或密码不正确');
           }
       }
     }
    /**
     * 绑定手机接口
     */
    public function phone(){
            $header = Request::instance()->header();
            $token  = $header['token'];
            $phone  = $_POST['phone'];
            $code  =$_POST['code'];


            $res  = Db::name('phone')->where(array(
                'phone'=>$phone,
                'code'=>$code
            ))
                ->find();

            if($res){
                $data['phone']=$phone;
                $data['regtime']=date('Y-m-d H:i:s',time());
                Db::name('user')->where(array(
                    'token'=>$token
                ))->update($data);
                $this->show(1,'绑定成功');
            }else{
                $this->show(0,'绑定失败');
            }


    }


    /**
     * 短信
     */
    public function msg(){
       if($_POST){
         $phone  = $_POST['phone'];
         $code  =rand(1000,9999);
           $url = "http://v.juhe.cn/sms/send";
           $params = array(
               'key'   => '777a648c0d48972ddacd22656893968c', //您申请的APPKEY
               'mobile'    => $phone, //接受短信的用户手机号码
               'tpl_id'    => '212987', //您申请的短信模板ID，根据实际情况修改
               'tpl_value' =>'#code#='.$code.'' //您设置的模板变量，根据实际情况修改
           );

           $paramstring = http_build_query($params);
           $content = $this->juheCurl($url, $paramstring);
           $result = json_decode($content, true);
           if ($result) {

               if($result['reason']=="操作成功"){
                   //将手机号和验证码存储
                   $data['phone'] =$phone;
                   $data['code'] = $code;
                   $data['uptime'] = date('Y-m-d H:i:s',time());
                   Db::name('phone')->insert($data);
                       $this->show(1,'发送成功');

               }else{
                   $this->show(0,'发送失败');
               }
           } else {
               $this->show(0,'发送失败');
           }
       }

    }


    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    function juheCurl($url, $params = false, $ispost = 0)
    {
        $httpInfo = array();
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'JuheData');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url.'?'.$params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }

    /**
     * 请求用户信息接口
     */
    public function get_user(){

            $header = Request::instance()->header();
            $token  = $header['token'];

             $res  = Db::name('user')->where(array(
                 'token'=>$token,

             ))
                 ->find();

             if($res){
                 $this->show(1,'获取成功',$res);
             }else{
                 $this->show(0,'获取失败');
             }
         }

   /**
    * 获取楼盘信息列表
    */

    public function get_home(){

        $header = Request::instance()->header();
        $token  = $header['token'];
        $user = Db::name('user')->where(array(
            'token'=>$token
        ))->find();
        if($user){
            if($_POST['city']&&$_POST['region']){
                $res  = Db::name('home')
                    ->order('uptime desc')
                    ->where(array(
                        'city'=>$_POST['city'],
                        'region'=>$_POST['region']
                    ))
                    ->select();
                for($i=0;$i<count($res);$i++){
                    $res[$i]['pic'] = 'https://ck.51tuanke.com/fang/public'.substr($res[$i]['pic'],1,17);
                    if($res[$i]['price'] == 0 ){
                        $res[$i]['price'] ='待定';
                    }else{
                        $res[$i]['price'] = '均价'.$res[$i]['price'].'/㎡';
                    }
                }

                if($res){
                    $this->show(1,'获取成功',$res);
                }else{
                    $this->show(1,'数组为空');
                }
            }elseif ($_POST['city']){
                $res  = Db::name('home')
                    ->order('uptime desc')
                    ->where(array(
                        'city'=>$_POST['city'],
                    ))
                    ->select();
                for($i=0;$i<count($res);$i++){
                    $res[$i]['pic'] = 'https://ck.51tuanke.com/fang/public'.substr($res[$i]['pic'],1,17);
                    if($res[$i]['price'] == 0 ){
                        $res[$i]['price'] ='待定';
                    }else{
                        $res[$i]['price'] = '均价'.$res[$i]['price'].'/㎡';
                    }
                }

                if($res){
                    $this->show(1,'获取成功',$res);
                }else{
                    $this->show(1,'数组为空');
                }
            }
            else{
                $res  = Db::name('home')
                    ->order('uptime desc')
                    ->select();
                for($i=0;$i<count($res);$i++){
                    $res[$i]['pic'] = 'https://ck.51tuanke.com/fang/public'.substr($res[$i]['pic'],1,17);
                    if($res[$i]['price'] == 0 ){
                        $res[$i]['price'] ='待定';
                    }else{
                        $res[$i]['price'] = '均价'.$res[$i]['price'].'/㎡';
                    }
                }

                if($res){
                    $this->show(1,'获取成功',$res);
                }else{
                    $this->show(1,'数组为空');
                }
            }

        }else{

        }


    }

    /**
     * 城市
     */
    public function get_city(){
        $header = Request::instance()->header();
        $token  = $header['token'];
        $user = Db::name('user')->where(array(
            'token'=>$token
        ))->find();
        if($user){
            $res  = Db::name('city')
                ->order('uptime desc')
                ->select();
            for($i=0;$i<count($res);$i++){
               $region[$i] = DB::name('region')->where(array(
                   'city_id'=>$res[$i]['id']
               ))->select();
               $res[$i]['region'] = $region[$i];
            }
            if($res){
                $this->show(1,'获取成功',$res);
            }else{
                $this->show(0,'获取失败');
            }
        }


}

    /**
     * 新增推荐客户接口
     */
    public  function add_order(){
        $header = Request::instance()->header();
        $token  = $header['token'];
        $user = DB::name('user')->where(array(
            'token'=>$token
        ))->find();
        $_POST['user_name'] = $user['username'];
        $_POST['user_id'] = $user['id'];
        $_POST['uptime'] = date('Y-m-d H:i:s',time());
        $res = Db::name('order')->where(array(
            'username'=>$_POST['username'],
            'user_id'=>$user['id']
        ))->find();
        if($res){
            $this->show(0,'已添加，请勿重复添加');
        }else{
            $add = Db::name('order')->insert($_POST);
            if($add){
                $this->show(1,'添加成功');
            }else{
                $this->show(0,'添加失败');
            }
        }

    }

    /**
     * 我的推荐客户接口
     */
    public function my(){
        $header = Request::instance()->header();
        $token  = $header['token'];
        $user = DB::name('user')->where(array(
            'token'=>$token
        ))->find();

        //搜索
        if($_POST['search']){
                $search =  $_POST['search'];

                $where['username'] = array('like', '%' . $search . '%');
//                $where['phone'] = array('like', '%' . $search . '%');
                $res['data'] = Db::name('order')
//                    ->where($where)
                    ->where(array(
                        'user_id'=>$user['id'],
                        'username'=>array('like', '%' . $search . '%'),
//                        'phone'=>array('like', '%' . $search . '%')
                    ))
                    ->order('uptime desc')
                    ->select();
//                print_r($res);


        }else{
            $page = $_POST['page'];
            $pageSize = $_POST['pageSize'];
            $res['data'] = Db::name('order')
//                ->limit($page*$pageSize-($pageSize-1),$pageSize*$page)

                ->where(array(
                    'user_id'=>$user['id']
                ))
                ->order('uptime desc')
                ->page($page,$pageSize)
                ->select();

            $res['sum']  = Db::name('order')->count();
            $res['page_num']  = $page;
        }

        if($res){
            $this->show(1,'获取成功',$res);
        }else{
                $this->show(0,'获取失败');
        }
    }



    /**
     *根据id 获取房产信息
     */
    public function get_home_id(){
        $header = Request::instance()->header();
        $token  = $header['token'];
        $user = Db::name('user')->where(array(
            'token'=>$token
        ))->find();
        if($user){
            $res['detail']  = Db::name('home')
                   ->where(array(
                       'id'=>$_POST['id']
                   ))->find();

                $res['detail']['pic'] = 'https://ck.51tuanke.com/fang/public'.substr($res['detail']['pic'],1,17);
            if($res['detail']['price'] == 0 ){
                $res['detail']['price'] ='待定';
            }else{
                $res['detail']['price'] = '均价'.$res['detail']['price'].'/㎡';
            }
            $lun = Db::name('lun')  ->order('order ')->where(array(
                'home_id'=>$res['detail']['id']
            ))->select();
            for($i=0;$i<count($lun);$i++){
                $lun[$i]['pic'] =  'https://ck.51tuanke.com/fang/public'.substr($lun[$i]['pic'],1,18);
            }
            $hu = Db::name('hu')  ->order('uptime desc')->where(array(
                'home_id'=>$res['detail']['id']
            ))->select();
            for($y=0;$y<count($hu);$y++){
                $hu[$y]['pic'] =  'https://ck.51tuanke.com/fang/public'.substr($hu[$y]['pic'],1,18);
            }
            $res['lun'] = $lun;
            $res['hu'] = $hu;

            if($res){
                $this->show(1,'获取成功',$res);
            }else{
                $this->show(0,'获取失败');
            }
        }
    }


}